import 'package:flower/components/custom_toast.dart';
import 'package:flower/config/service_url.dart';
import 'package:flower/model/address_model.dart';
import 'package:flower/model/base_model.dart';
import 'package:flower/pages/tabs/user/children/address.dart';
import 'package:flower/utils/http_util.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

class AddressAdd extends StatefulWidget {
  final int? addressId;
  const AddressAdd({super.key, this.addressId});

  @override
  State<AddressAdd> createState() => _AddressAddState();
}

class _AddressAddState extends State<AddressAdd> {
  final _formKey = GlobalKey<FormState>();
  String _name = '';
  String _phoneNumber = '';
  String _detailedAddress = '';
  bool _isDefault = false;

  @override
  void initState() {
    super.initState();
    queryAddress();
  }

  void queryAddress() async {
    if (widget.addressId != null) {
      Map<String, dynamic> map = <String, dynamic>{};
      map["aid"] = widget.addressId;

      Response response =
          await HttpUtil.get(getAddressById, queryParameters: map);
      AddressDataModel addressModel = AddressDataModel.fromJson(response.data);

      if (addressModel.code == 1) {
        AddressData addressData = addressModel.data;
        _name = addressData.consignee;
        _phoneNumber = addressData.phone;
        _detailedAddress = addressData.detail;
        _isDefault = addressData.isDefault == 1 ? true : false;
      }
    }
  }

  Future<void> _submitAddress() async {
    if (_formKey.currentState?.validate() ?? false) {
      // 构建请求数据
      Map<String, dynamic> map = <String, dynamic>{};
      map["consignee"] = _name;
      map["phone"] = _phoneNumber;
      map["detail"] = _detailedAddress;
      map["isDefault"] = _isDefault ? 1 : 0;
      Response result = await HttpUtil.post(addAddress, queryParameters: map);

      BaseModel baseModel = BaseModel.fromJson(result.data);
      if (baseModel.code == 1) {
        // 请求成功，处理响应
        CustomToast.showSuccessToast("添加地址成功");
        Navigator.of(context).push(
          MaterialPageRoute(
            builder: (context) => const Address(),
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    var textStyle = TextStyle(fontSize: 15, color: Color(0xFF303133));
    var border = BorderSide(width: 1, color: Color(0xFFF5F5F5));
    var boxDecoration =
        BoxDecoration(color: Colors.white, border: Border(bottom: border));

    InputDecoration inputDecoration = InputDecoration(
      border: OutlineInputBorder(
        borderSide: BorderSide(color: Color(0xFFE0E0E0)),
        borderRadius: BorderRadius.circular(5),
      ),
      focusedBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Color(0xFFFA436A)),
        borderRadius: BorderRadius.circular(5),
      ),
      contentPadding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
    );

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: const Text("新增收货地址",
            style: TextStyle(fontSize: 16, color: Colors.black)),
        centerTitle: true,
      ),
      body: Container(
        color: Color(0xFFF5F5F5),
        width: MediaQuery.of(context).size.width,
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              Container(
                margin: const EdgeInsets.only(top: 5),
                padding: const EdgeInsets.all(15),
                decoration: boxDecoration,
                child: Row(
                  children: [
                    Expanded(
                      flex: 1,
                      child: Text("姓名", style: textStyle),
                    ),
                    Expanded(
                      flex: 4,
                      child: TextFormField(
                        initialValue: _name,
                        decoration: inputDecoration,
                        style: textStyle,
                        onChanged: (value) {
                          setState(() {
                            _name = value;
                          });
                        },
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                padding: const EdgeInsets.all(15),
                decoration: boxDecoration,
                child: Row(
                  children: [
                    Expanded(
                      flex: 1,
                      child: Text("手机号码", style: textStyle),
                    ),
                    Expanded(
                      flex: 4,
                      child: TextFormField(
                        initialValue: _phoneNumber,
                        decoration: inputDecoration,
                        style: textStyle,
                        keyboardType: TextInputType.phone,
                        onChanged: (value) {
                          setState(() {
                            _phoneNumber = value;
                          });
                        },
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                padding: const EdgeInsets.all(15),
                decoration: boxDecoration,
                child: Row(
                  children: [
                    Expanded(
                      flex: 1,
                      child: Text("详细地址", style: textStyle),
                    ),
                    Expanded(
                      flex: 4,
                      child: TextFormField(
                        initialValue: _detailedAddress,
                        decoration: inputDecoration,
                        style: textStyle,
                        onChanged: (value) {
                          setState(() {
                            _detailedAddress = value;
                          });
                        },
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                color: Colors.white,
                margin: const EdgeInsets.only(top: 8, bottom: 20),
                padding:
                    const EdgeInsets.symmetric(vertical: 7, horizontal: 15),
                child: Row(
                  children: [
                    Expanded(
                      flex: 1,
                      child: Text("设为默认", style: textStyle),
                    ),
                    Switch(
                      value: _isDefault,
                      materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      onChanged: (value) {
                        setState(() {
                          _isDefault = value;
                        });
                      },
                      activeColor: Colors.white,
                      activeTrackColor: Color(0xFFFA436A),
                    ),
                  ],
                ),
              ),
              InkWell(
                onTap: _submitAddress,
                child: Container(
                  alignment: Alignment.center,
                  width: MediaQuery.of(context).size.width,
                  height: 40,
                  margin: const EdgeInsets.all(15),
                  decoration: BoxDecoration(
                    color: Color(0xFFFA436A),
                    borderRadius: BorderRadius.circular(5),
                  ),
                  child: const Text(
                    '提交',
                    style: TextStyle(color: Colors.white, fontSize: 16),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
